package com.caiwangdai.app.backend

import com.caiwangdai.app.BuildConfig
import com.caiwangdai.app.backend.api.HomeApi
import com.caiwangdai.app.backend.api.UserApi
import com.caiwangdai.app.backend.utils.OKHttpsUtils
import com.google.gson.GsonBuilder
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


object RetrofitHome {

    private const val HOST_API: String = BuildConfig.HOST

    private var retrofit: Retrofit
    private var isChangeBaseUrl = false//是否修改了BaseUrl


    //构造方法
    init {
        val gson = GsonBuilder()
                .setLenient()
                .create()

        retrofit = Retrofit.Builder()
                .client(OKHttpsUtils.getHttpClient())
                .addConverterFactory(GsonConverterFactory.create(gson))//Gson进行转化
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//RxJava进行一处处理
                .baseUrl(HOST_API)
                .build()
    }


    fun getRetrofit(): Retrofit = retrofit

    //service
    private var userApi: UserApi? = null
    private var homeApi: HomeApi? = null


    fun getHomeApi(): HomeApi {
        checkBaseUrl()
        homeApi = homeApi ?: retrofit.create<HomeApi>(HomeApi::class.java)
        return homeApi!!
    }


    fun getUserApi(): UserApi {
        checkBaseUrl()
        userApi = userApi ?: retrofit.create<UserApi>(UserApi::class.java)
        return userApi!!
    }


    //检查是否修改BaseUrl是否有修改
    private fun checkBaseUrl() {
        if (isChangeBaseUrl) {
            isChangeBaseUrl = false
        } else {
            retrofit = retrofit.newBuilder().baseUrl(HOST_API).build()
        }
    }

    //修改BaseURl
    fun modifyBaseUrl(baseUrl: String): RetrofitHome {
        retrofit = retrofit.newBuilder().baseUrl(baseUrl).build()
        isChangeBaseUrl = true
        return this
    }


}